package com.example.myapplication.ad

import android.view.View
import android.view.ViewGroup
import com.example.myapplication.appViewModel
import com.example.myapplication.network.LaunchInfo
import com.example.myapplication.utils.SPUtils

/**
 * 广告管理
 *
 * @constructor Create empty Ad manager
 */
abstract class AdManager {
    protected var locationId: String? = null

    /**
     * 加载广告
     *
     * @param locationId
     * @param shouldShow
     */
    abstract fun loadAd(locationId: String?, count: Int = 1, shouldShow: Boolean = true, isFullScreen: Boolean = false)

    /**
     * 广告加载成功后，展示广告
     */
    abstract fun showAd()

    /**
     * 广告加载监听器
     */
    abstract fun initListeners(shouldShow: Boolean)

    /**
     * 在onDestroy中销毁广告
     * ad?.destroy()
     */
    abstract fun destroyAD()

    companion object {
        const val TAG: String = "AdManager"

        val preShowTime: MutableMap<String, Long> = mutableMapOf()

        init {
            preShowTime.putAll(SPUtils.getRuleTime())
        }

        fun saveAdShowRule() {
            SPUtils.saveRuleTime(preShowTime)
        }

        fun removeFromParent(view: View?) {
            val vp = view?.parent
            if (vp is ViewGroup) {
                vp.removeView(view)
            }
        }

        fun getCodeId(locationId: String): LaunchInfo.AdSlot? {
            return appViewModel.launchData.value?.adSlot?.find { it.id == locationId }
        }

        fun needShow(locationId: String?): Boolean {
            if (locationId.isNullOrEmpty()) return false
            val ad: LaunchInfo.AdSlot? = getCodeId(locationId)
            return !(ad == null || !ad.state || System.currentTimeMillis() - preShowTime.getOrDefault(
                locationId,
                0
            ) < ad.interval * 1000)
        }
    }
}